<template>
  <div id="stores_cate_create"
       class="Row_content"
       style="width:560px;">
    <Form ref="formValidate"
          :model="formValidate"
          :rules="ruleValidate"
          :label-width="110">
      <FormItem label="所属组织："
                prop="parentId"
                :rules="{required:true, message: '所属组织不能为空', trigger: 'blur'}">
        <Select v-model="formValidate.parentId"
                style="width:255px">
          <Option v-for="item in orgTagList"
                  :value="item.id"
                  :key="item.id">{{ item.tagName }}</Option>
        </Select>
      </FormItem>
      <FormItem label="分类名称："
                prop="classifyName">
        <Input v-model="formValidate.classifyName"
               placeholder="请输入"
               class='input-wid'
               :maxlength='10'
               @on-keyup='filterName'
               @on-blur="filterName"></Input>
      </FormItem>
      <FormItem label="上级分类："
                prop="preClassify">
        <Row type='flex'
             style="width:430px;">
          <Col>
          <Select v-model="formValidate.preClassify"
                  class='input-wid'
                  :disabled="disabled"
                  :clearable='true'>
            <Option v-for="(item, index) in preClassifyList"
                    :value="item.sysCategoryId"
                    :key="index">{{item.categoryName}}</Option>
          </Select>
          </Col>
          <Col style='margin-left:10px;color: #808695;'><span>不选择分类默认为顶级分类</span></Col>
        </Row>
      </FormItem>
      <FormItem label="关键词："
                prop="keyword">
        <Row type='flex'
             style="width:430px;">
          <Col>
          <Input v-model="formValidate.keyword"
                 placeholder="请输入"
                 class='input-wid'
                 :maxlength='30'></Input>
          </Col>
          <Col style='margin-left:10px;color: #808695;'><span>关键词用空格分割</span></Col>
        </Row>
      </FormItem>
      <FormItem label="是否显示："
                prop="isShow">
        <RadioGroup v-model="formValidate.isShow"
                    size="large">
          <Radio :label="1">显示</Radio>
          <Radio :label="0"
                 style="margin-left:50px">隐藏</Radio>
        </RadioGroup>
      </FormItem>
      <FormItem label="分类描述：">
        <div>
          <Input v-model="formValidate.remark"
                 type="textarea"
                 style="width:320px"
                 :maxlength='200'
                 :autosize="{ minRows: 5, maxRows: 8 }"
                 placeholder="请输入内容"></Input>
          <span class="rol_tipsd"
                style="width: 320px">{{desCount}}/200</span>
        </div>
      </FormItem>
      <FormItem>
        <Button type="primary"
                class="btn"
                @click="handleSubmit">确定</Button>
        <Button class="btn"
                style="margin-left: 24px"
                @click="handleReset">取消</Button>
      </FormItem>
    </Form>
  </div>
</template>

<script>
import Treeselect from '@riophae/vue-treeselect'
import '@riophae/vue-treeselect/dist/vue-treeselect.css'
import { routeEqual } from '@/libs/util'
import { getCategoryList, createCategory, getOrgTag } from '@/api/purchase/index.js'
export default {
  name: 'stores_cate_create',
  components: { Treeselect },
  computed: {
    desCount () {
      if (this.formValidate.remark) {
        return this.formValidate.remark.length
      } else {
        return 0
      }
    }
  },
  beforeRouteEnter (to, from, next) {
    next(vm => {
      if (vm.formValidate.preClassify !== to.query.id) {
        vm.formValidate.preClassify = to.query.id
      }
      if (to.query.id) {
        vm.disabled = true
      } else {
        vm.disabled = false
      }
    })
  },
  data () {
    return {
      submitLock: false,
      orgTagList: [],
      disabled: false,
      preClassifyList: [],
      formValidate: {
        classifyName: '',
        preClassify: '',
        keyword: '',
        remark: '',
        isShow: 1,
        parentId: null,
        orgName: ''
      },
      normalizer (node) {
        if (node.childList) {
          if (node.childList.length > 0) {
            return {
              id: node.id,
              label: node.orgName,
              children: node.childList
            }
          } else {
            return {
              id: node.id,
              label: node.orgName
            }
          }
        }
      },
      ruleValidate: {
        classifyName: { required: true, message: '请输入分类名称', trigger: 'blur' },
        parentId: { required: true, message: '请选择所属组织' },
        isShow: { required: true, message: '请选择是否显示' }
      }
    }
  },
  watch: {
    'formValidate.parentId' (val) {
      this.$refs.formValidate.validateField('parentId')
    }
  },
  methods: {
    filterName () {
      this.formValidate.classifyName = this.formValidate.classifyName.replace(/[^\u4e00-\u9fa5]/g, '')
    },
    handleSubmit () {
      this.$refs.formValidate.validate(valid => {
        if (valid) {
          this.getOrgName(this.orgTagList || [])
          let data = {
            merchantId: this.$store.state.user.merchantId,
            creator: this.$store.state.user.userId,
            creatorName: this.$store.state.user.userName,
            categoryName: this.formValidate.classifyName,
            categoryDesc: this.formValidate.remark,
            keyword: this.formValidate.keyword,
            display: this.formValidate.isShow,
            orgTagId: this.formValidate.parentId,
            orgTagName: this.formValidate.orgName
          }
          if (this.formValidate.preClassify) {
            data.parentId = this.formValidate.preClassify
          }
          if (!this.submitLock) {
            this.submitLock = true
            createCategory(data).then(res => {
              this.submitLock = false
              const result = res.data || {}
              if (result.status === 200) {
                this.$Message.success('新增成功！')
                this.handleReset()
              } else {
                this.$Message.error(`${result.message}`)
              }
            }).catch(err => {
              this.submitLock = false
              this.$Message.error(`${err}`)
            })
          }
        }
      })
    },
    getOrgName (arr) {
      arr.forEach(item => {
        if (item.id === this.formValidate.parentId) {
          this.formValidate.orgName = item.tagName
        }
      })
    },
    handleReset () {
      const type = this.$route.query.type
      this.$store.commit('closeTag', this.$route)
      this.$store.commit('setTagNavList', this.$store.state.app.tagNavList.filter(item => !routeEqual(this.$route, item)))
      if (type === '1') {
        this.$nextTick(() => {
          this.$router.push({
            name: 'stores_cate'
          })
        })
      } else if (type === '2') {
        this.$nextTick(() => {
          this.$router.push({
            name: 'stores_next_cate',
            query: {
              id: this.formValidate.preClassify
            }
          })
        })
      }
    },
    getAllCategory () {
      getCategoryList({
        merchantId: this.$store.state.user.merchantId,
        sortBy: 'ASC',
        level: 1,
        offset: 0,
        limit: 999999,
        orgTagId: this.orgTagList.map(item => item.id)
      }).then(res => {
        const result = res.data || {}
        if (result.status === 200) {
          this.preClassifyList = result.data.categories || []
        } else {
          this.$Message.error(`${result.message}`)
        }
      }).catch(err => {
        this.$Message.error(`${err}`)
      })
    }
  },
  mounted () {
    getOrgTag({
      merchantId: this.$store.state.user.merchantId,
      id: this.$store.state.user.orgId
    }).then(res => {
      if (res.data.status === 200) {
        this.orgTagList = res.data.data
        this.getAllCategory()
      } else {
        this.$Message.error(`${res.data.error}`)
      }
    })
    if (this.$route.query.id) {
      this.formValidate.preClassify = this.$route.query.id
      this.disabled = true
    } else {
      this.formValidate.preClassify = ''
      this.disabled = false
    }
  }
}
</script>

<style scoped>
.input-wid {
  width: 260px;
}
.btn {
  width: 100px;
}
</style>
